package com.zmn.oms.zmn.normal.business.impl.work.financework;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.zmn.base.engineer.dubbo.interfaces.foreign.EngineerListRemoteService;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.math.MathUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.dms.common.enums.DiscountTypeEnums;
import com.zmn.manager.mq.interfaces.ZmnMQSender;
import com.zmn.oms.business.interfaces.conf.checkout.ConfCheckoutBService;
import com.zmn.oms.business.interfaces.discount.OrderDiscountBService;
import com.zmn.oms.business.interfaces.warranty.OrderWarrantyBService;
import com.zmn.oms.common.annotation.ZsNormalOrderWorkLog;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderLogConsts;
import com.zmn.oms.common.constant.OrderPayConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.constant.MessageQueueTopicConstant;
import com.zmn.oms.manager.utils.OmsMqTagConsts;
import com.zmn.oms.model.dto.work.modify.must.ZsCheckOutDTO;
import com.zmn.oms.model.entity.conf.checkout.ConfCheckout;
import com.zmn.oms.model.entity.conf.checkout.ConfCheckoutQuery;
import com.zmn.oms.model.entity.discount.OrderDiscount;
import com.zmn.oms.model.entity.fcorderpart.OrderFactoryPart;
import com.zmn.oms.model.entity.master.OrderMaster;
import com.zmn.oms.model.entity.part.OrderPart;
import com.zmn.oms.model.entity.part.OrderPartAddition;
import com.zmn.oms.model.entity.pay.OrderPay;
import com.zmn.oms.model.entity.serviceitem.OrderServiceItem;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.vo.serviceitem.ServiceItemVO;
import com.zmn.oms.model.vo.work.modify.must.ZsAccountMasterPartVO;
import com.zmn.oms.model.vo.work.modify.must.ZsCheckOutMasterVO;
import com.zmn.oms.model.vo.work.modify.must.ZsCheckOutVO;
import com.zmn.oms.model.vo.work.modify.must.ZsUpdateOrderInternalPriceServiceItemVO;
import com.zmn.oms.services.interfaces.comment.OrderCommentService;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.discount.OrderDiscountService;
import com.zmn.oms.services.interfaces.factory.OrderFactoryService;
import com.zmn.oms.services.interfaces.fcorderpart.OrderFactoryPartService;
import com.zmn.oms.services.interfaces.invoice.OrderInvoiceService;
import com.zmn.oms.services.interfaces.master.OrderMasterService;
import com.zmn.oms.services.interfaces.member.OrderMemberService;
import com.zmn.oms.services.interfaces.order.OrderExtendService;
import com.zmn.oms.services.interfaces.part.OrderPartAdditionService;
import com.zmn.oms.services.interfaces.part.OrderPartService;
import com.zmn.oms.services.interfaces.pay.OrderPayService;
import com.zmn.oms.services.interfaces.serviceitem.OrderServiceItemService;
import com.zmn.oms.services.interfaces.work.OrderWorkAmountService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.services.interfaces.work.financework.FinanceWorkService;
import com.zmn.oms.zmn.business.interfaces.work.orderpay.ZsOrderPayBService;
import com.zmn.oms.zmn.normal.business.interfaces.order.ZsNormalOrderBService;
import com.zmn.oms.zmn.normal.business.interfaces.work.financework.ZsNormalFinanceWorkBService;
import com.zmn.pay.common.constant.PayConsts;
import com.zmn.performance.dubbo.interfaces.order.OrderEffectivenessListRemoteService;
import com.zmn.scm2.common.model.dio.scm.maintenance.order.use.MaintenanceOrderUseDIO;
import com.zmn.scm2.common.model.dio.scm.maintenance.order.use.item.MaintenanceOrderUseItemDIO;
import com.zmn.scm2.common.model.dio.scm.purchase.apply.ScmPurchaseApplyDIO;
import com.zmn.scm2.common.model.dro.scm.engineer.ScmSubjectDRO;
import com.zmn.scm2.dubbo.interfaces.scm.maintenance.order.use.MaintenanceOrderUseListRemoteService;
import com.zmn.scm2.dubbo.interfaces.scm.maintenance.order.use.MaintenanceOrderUseModifyRemoteService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static java.math.BigDecimal.ZERO;
import static java.math.RoundingMode.HALF_UP;

/**
 * 类描述：财务工单业务实现
 *
 * @author lujia
 * @date 2018/11/02 21:02
 */
@Service
public class ZsNormalFinanceWorkBServiceImpl implements ZsNormalFinanceWorkBService {

    private static final Logger logger = LoggerFactory.getLogger(ZsNormalFinanceWorkBServiceImpl.class);

    private static final List<Integer> erpCities = Lists.newArrayList(500100);

    @Autowired
    protected OrderWorkService orderWorkService;

    @Autowired
    protected OrderDetailService orderDetailService;

    @Autowired
    protected OrderExtendService orderExtendService;

    @Autowired
    protected OrderMasterService orderMasterService;

    @Autowired
    protected FinanceWorkService financeWorkService;

    @Autowired
    protected OrderPartService orderPartService;

    @Autowired
    protected OrderDiscountService orderDiscountService;

    @Autowired
    protected OrderInvoiceService orderInvoiceService;

    @Autowired
    protected ZsOrderPayBService zsOrderPayBService;

    @Autowired
    protected OrderFactoryService orderFactoryService;

    @Autowired
    protected OrderDiscountBService orderDiscountBService;

    @Resource
    protected ZmnMQSender zmnMQSender;

    @Autowired
    protected OrderWarrantyBService orderWarrantyBService;

    @Autowired
    OrderWorkAmountService orderWorkAmountService;

    @Autowired
    OrderCommentService orderCommentService;

    @Autowired
    OrderServiceItemService orderServiceItemService;

    @Autowired
    OrderMemberService orderMemberService;

    @Autowired
    ConfCheckoutBService confCheckoutBService;

    @Autowired
    OrderFactoryPartService orderFactoryPartService;

	@Autowired
	OrderPayService orderPayService;

	@Autowired
    ZsNormalOrderBService zsNormalOrderBService;

    @Autowired
    OrderPartAdditionService orderPartAdditionService;

    //@Autowired
    //private EsOrderWorkService esOrderWorkService;
    //@Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    //EngineerListRemoteService engineerListRemoteService;

    // @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    // CoupRemoteService coupRemoteService;

    // @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    // SubsidyRuleConfigListRemoteService subsidyRuleConfigListRemoteService;
    //@Reference(version = com.zmn.base.engineer.common.constants.DubboConsts.INTERFACE_VERSION, check = false)
    //private EngineerProductGroupListRemoteService engineerProductGroupListRemoteService;
    @Autowired
    private ZsNormalFinanceWorkBService zsNormalFinanceWorkBService;

    // @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    // private BonusConfigListRemoteService bonusConfigListRemoteService;
    @Reference(version = com.zmn.performance.dubbo.consts.DubboConsts.INTERFACE_VERSION, check = false)
    private OrderEffectivenessListRemoteService orderEffectivenessListRemoteService;
    @Reference(version = com.zmn.scm2.dubbo.interfaces.utils.DubboConsts.INTERFACE_VERSION, check = false)
    private MaintenanceOrderUseModifyRemoteService maintenanceOrderUseModifyRemoteService;
    @Reference(version = com.zmn.scm2.dubbo.interfaces.utils.DubboConsts.INTERFACE_VERSION, check = false)
    private MaintenanceOrderUseListRemoteService maintenanceOrderUseListRemoteService;

    @Override
    public ZsCheckOutVO findCheckoutVo(Long orderId, Long workId, Integer operateId) {

        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
        ZsCheckOutVO checkOutVO = new ZsCheckOutVO();
        BeanUtils.copyProperties(orderWork, checkOutVO);

        // 计算开票金额（应收-配件）
        checkOutVO.setBillAmount(MathUtil.sub(orderWork.getTotalAmount(), orderWork.getPartAmount()));
        // 计算配件占比
        boolean amountBoolean = checkOutVO.getPartAmount() != null && checkOutVO.getTotalAmount() != null;
        if (amountBoolean) {
            BigDecimal partAmount = BigDecimal.valueOf(checkOutVO.getPartAmount());
            BigDecimal receivables = BigDecimal.valueOf( checkOutVO.getTotalAmount());
            checkOutVO.setProportionAmount(getRate(partAmount, receivables).toString());
        } else {
            checkOutVO.setProportionAmount("0");
        }

        // 收费项目
        List<OrderServiceItem> orderServiceItems = orderServiceItemService.listByOrderId(orderWork.getOrderId());
        checkOutVO.setOrderServiceItemList(this.personToServiceItemVO(orderServiceItems));
        // 内部总价
        checkOutVO.setInternalTotalPrice(orderServiceItems.stream()
                .filter(e -> e.getInternalTotalPrice() != null)
                .mapToInt(OrderServiceItem::getInternalTotalPrice).sum());

        // 收单配置
        ConfCheckoutQuery confCheckoutQuery = ConfCheckoutQuery.builder().plat(orderWork.getPlatWork())
                .servCategId(orderWork.getServCategId())
                .categOneId(orderWork.getCategOneId())
                .categTwoId(orderWork.getCategId())
                .status(com.zmn.consts.GlobalConsts.YES).build();
        ConfCheckout checkOutConf = confCheckoutBService.getConfByQuery(confCheckoutQuery);
        checkOutVO.setCheckOutConf(checkOutConf);
        // 订单金额
        Integer amount = orderWork.getOriginalAmount();
        if (Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_NEW)) {
            // 收单标准 if 有优惠 订单金额 - 优惠金额(只算人工优惠) else 订单金额
            List<OrderDiscount> orderDiscountList = orderDiscountService.listByOrderId(orderWork.getOrderId());
            if (CollectionUtils.isNotEmpty(orderDiscountList)) {
                int artificialAmount = orderDiscountList.stream().filter(item -> Objects.equals(item.getCateg(), DiscountTypeEnums.DISCOUNT_RULE_ARTIFICIAL.getSubType()))
                        .mapToInt(OrderDiscount::getAmount).sum();
                if (Objects.nonNull(amount) && NumberUtil.isNotNullOrZero(artificialAmount)) {
                    amount = amount - artificialAmount;
                }
            }
        }
        if (Objects.isNull(checkOutConf.getAmount()) || (Objects.nonNull(amount) && amount >= checkOutConf.getAmount())) {
            checkOutVO.setResultStatus(OrderStatusConsts.WORK_RESULT_SUCCESS);
        } else {
            checkOutVO.setResultStatus(OrderStatusConsts.WORK_RESULT_FAIL);
        }

        //        OrderExtend orderExtend = orderExtendService.findOrderExtendByOrderId(orderId);
        // 子公司老总&总部角色：重复收单时，无：贴花照片
        //        if (orderWork.getStatus() >= OrderStatusConsts.WORK_STATUS_CHECKOUT && Objects.equals(OrderConsts
        //        .ORDER_OP_TYPE_ADMIN_CHECKOUT, operateId)) {
        //            // empty
        //        } else {
        //            // 查询贴花数据
        //            if (orderExtend != null && StringUtil.isNotBlank(orderExtend.getAppliqueSrc())) {
        //                String[] appliqueSrcArr = orderExtend.getAppliqueSrc().split(",");
        //                checkOutVO.setAppliqueSrcList(Lists.newArrayList(appliqueSrcArr));
        //            }
        //        }
        // 查询工程师照片
        //        if (orderExtend != null && StringUtil.isNotBlank(orderExtend.getMasterSrc())) {
        //            checkOutVO.setMasterImageSrc(orderExtend.getMasterSrc());
        //        }

        // 上月派单，下月5号往后收单，无法勾选有效无效
        //        Date distributeTime = orderWork.getDistributeTime();
        //        boolean supportOperate = DateUtil.isCurMonthOrBetween1to5Day(distributeTime);
        //        checkOutVO.setOperateApplique(supportOperate ? GlobalConsts.YES : GlobalConsts.NO);



        // 查询开票数据
        List<ZsCheckOutMasterVO> checkOutMasterVOList = Lists.newArrayList();
        List<OrderMaster> masterList = orderMasterService.listMasterByWorkId(orderId, workId);
        masterList.forEach((master) -> {
            ZsCheckOutMasterVO zsCheckOutMasterVO = new ZsCheckOutMasterVO();
            zsCheckOutMasterVO.setMasterId(master.getMasterId());
            zsCheckOutMasterVO.setMasterName(master.getMasterName());
            zsCheckOutMasterVO.setMasterPhone(master.getMasterPhone());
            String orderMasterTypeName = OrderConsts.getOrderMasterTypeName(master.getType());
            zsCheckOutMasterVO.setMasterTypeName(orderMasterTypeName);
            checkOutMasterVOList.add(zsCheckOutMasterVO);
        });
        checkOutVO.setCheckOutMasterVOList(checkOutMasterVOList);

        return checkOutVO;
    }

    /**
     * 保存收单-门脸（入口）
     *
     * @param checkOutDto
     */
    @Override
    public void saveFacadeCheckOut(ZsCheckOutDTO checkOutDto) throws Exception {

        // 处理内采配件的算账主体
        List<OrderPart> list = orderPartService.listByOrderId(checkOutDto.getOrderId());

        Map<Integer, List<OrderPart>> partMasterMap = list.stream()
                .filter(part -> NumberUtil.isNullOrZero(part.getSettlementSubjectType()))
                .collect(Collectors.groupingBy(OrderPart::getMasterId));
        logger.info("处理内采配件的算账主体:{}", partMasterMap);
        if (CollectionUtil.isNotNullOrEmpty(partMasterMap)) {
            partMasterMap.forEach((masterId, partList) -> {
                Long orderId = partList.get(0).getOrderId();

                logger.info("查询工单算账主体 入参:orderId:{} masterId:{}", orderId, masterId);
                com.zmn.common.dto2.ResponseDTO<List<ScmSubjectDRO>> responseDTO = maintenanceOrderUseListRemoteService.listSubjectByWorkIdAndMasterIdAndGoodsId(orderId, (long)masterId);
                logger.info("查询工单算账主体 出参:{}", JSON.toJSONString(responseDTO));
                if (responseDTO.isSuccess() && CollectionUtil.isNotNullOrEmpty(responseDTO.getData())) {
                    Map<String, Map<String, List<OrderPart>>> orderPartMap = partList.stream().collect(Collectors.groupingBy(OrderPart::getPartId, Collectors.groupingBy(OrderPart::getDrawId)));
                    Map<String, Map<String, ScmSubjectDRO>> goodsSubjectMap = responseDTO.getData().stream().collect(Collectors.groupingBy(ScmSubjectDRO::getGoodsId, Collectors.toMap(ScmSubjectDRO::getSaleOrderId, Function.identity(), (v1, v2) -> v1)));

                    goodsSubjectMap.forEach((goodsId, childMap) -> {
                        childMap.forEach((saleOrderId, dro) -> {
                            Map<String, List<OrderPart>> goodsPartListMap = orderPartMap.get(goodsId);
                            if (CollectionUtil.isNotNullOrEmpty(goodsPartListMap)) {
                                List<OrderPart> goodsPartList = goodsPartListMap.get(saleOrderId);
                                if (CollectionUtil.isNotNullOrEmpty(goodsPartList)) {
                                    goodsPartList.forEach(part -> {
                                        part.setSettlementSubjectType(Optional.ofNullable(dro.getSettlementSubjectType()).orElse(GlobalConsts.NONE));
                                        orderPartService.updateSettlementSubjectTypeByOrderPartId(part);
                                    });
                                }
                            }
                        });
                    });
                }
            });
        }
        // 判断不予报销，系统自动报销成不予报销状态
        try {
            OrderWork orderWork = orderWorkService.findOrderWorkByKeySrcMaster(checkOutDto.getOrderId(), checkOutDto.getWorkId());
            boolean noReimbursement = zsNormalOrderBService.isNoReimbursement(orderWork);
            if (noReimbursement) {
                zsNormalOrderBService.saveSysPartReimburse(checkOutDto.getOrderId(), checkOutDto.getWorkId(), list);
            }
        } catch (Exception e) {
            logger.error("不予报销-系统设置报销状态异常：" +e.getMessage(),e);
            throw new OmsBaseException("系统自动报销失败");
        }

        zsNormalFinanceWorkBService.saveCheckout(checkOutDto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_CHECKOUT, beforeProceed = false)
    public void saveCheckout(ZsCheckOutDTO checkOutDto) throws Exception {

        OrderWork orderWork = orderWorkService.findOrderWorkByKeySrcMaster(checkOutDto.getOrderId(), checkOutDto.getWorkId());
        if (orderWork.getStatus() < OrderStatusConsts.WORK_STATUS_COMPLETE) {
            throw new OmsBaseException("该工单没有完成，不能收单");
        }

        if (orderWork.getStatus() == OrderStatusConsts.WORK_STATUS_ACCOUNT || orderWork.getAccountTime() != null) {
            throw new OmsBaseException("该工单已经被算账，不能收单");
        }

        // 有待提交的外报配件不允许收单
        OrderPartAddition orderPartAddition = orderPartAdditionService.findById(checkOutDto.getOrderId(), checkOutDto.getWorkId());
        if (Objects.nonNull(orderPartAddition) && Objects.equals(orderPartAddition.getReviewStatus(), GlobalConsts.LEVEL_4)) {
            throw new OmsBaseException("该工单存在待提交配件，不能收单");
        }

        List<ServiceItemVO> serviceItemVOS = checkOutDto.getServiceItemVOList();
        // 内采配件金额不能大于内部价
        if (Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_NEW)) {
            if (CollectionUtil.isNotNullOrEmpty(serviceItemVOS)){
                int internalSettlementPrice = serviceItemVOS.stream()
                        .filter(e -> e.getInternalTotalPrice() != null)
                        .mapToInt(ServiceItemVO::getInternalTotalPrice).sum();
                Integer partAmount = Optional.ofNullable(orderWork.getInSourcingAmount()).orElse(0);
                if (partAmount > internalSettlementPrice) {
                    throw new OmsBaseException("内采配件金额大于订单内部价，不能收单");
                }
            }
        }

        // 修改服务项内部价

        if (CollectionUtil.isNotNullOrEmpty(serviceItemVOS)){
            serviceItemVOS.forEach(item -> {
                OrderServiceItem serviceItem = new OrderServiceItem();
                serviceItem.setOrderId(checkOutDto.getOrderId());
                serviceItem.setProExtId(item.getProExtId());
                serviceItem.setServItemId(item.getServItemId());
                serviceItem.setInternalSettlementPrice(item.getInternalSettlementPrice());
                serviceItem.setInternalTotalPrice(item.getInternalTotalPrice());
                orderServiceItemService.updateInternalPriceByKey(serviceItem);
            });
        }

        // 收单时间
        Date checkoutTime = Optional.ofNullable(orderWork.getCheckoutTime()).orElse(DateUtil.getNow());

        // 保存工单收单信息
        OrderWork checkoutWork = new OrderWork();
        checkoutWork.setOrderId(checkOutDto.getOrderId());
        checkoutWork.setWorkId(checkOutDto.getWorkId());
        checkoutWork.setCheckoutTime(checkoutTime);
        checkoutWork.setCheckouterId(checkOutDto.getOperatorId());
        checkoutWork.setStatus(OrderStatusConsts.WORK_STATUS_CHECKOUT);
        checkoutWork.setResulterType(checkOutDto.getOperatorType());
        checkoutWork.setResulterId(checkOutDto.getOperatorId());
        checkoutWork.setResultStatus(checkOutDto.getResultStatus());
        checkoutWork.setResultTime(DateUtil.getNow());
        //checkoutWork.setAppliqueStatus(checkOutDto.getAppliqueStatus());
        //checkoutWork.setMasterImageStatus(checkOutDto.getMasterImageStatus());
        financeWorkService.updateCheckout(checkoutWork);

        // 写日志设置状态
        checkOutDto.setStatus(checkoutWork.getStatus());
        checkOutDto.setResultStatus(checkoutWork.getResultStatus());

        // 如果重复收单则不向供应链服务发送任何消息
        if (Objects.equals(orderWork.getStatus(), OrderStatusConsts.WORK_STATUS_CHECKOUT)){
            return;
        }

        // 退款单不用调scm2接口
        if (Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_NEW) || Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_REWORK)) {
            MaintenanceOrderUseDIO dio = new MaintenanceOrderUseDIO();
            dio.setWorkId(orderWork.getWorkId());
            dio.setPlat(orderWork.getPlatWork());
            dio.setStatus(GlobalConsts.YES);
            dio.setType(GlobalConsts.NO);
            // 如果是厂商单，则收单时把厂商配件同步给scm2。   工单内采配件也要重新传一次，做最后的确认
            if (Objects.equals(orderWork.getSourceType(), OrderConsts.ORDER_SOURCE_TYPE_FACTORY)) {
                dio.setGoodsTypes(OrderConsts.PART_TYPE_FACTORY);
                List<OrderFactoryPart> factoryParts = orderFactoryPartService.listByOrderId(orderWork.getOrderId());

                List<MaintenanceOrderUseItemDIO> skuDIOList = Lists.newArrayList();
                factoryParts.forEach(p -> {
                    MaintenanceOrderUseItemDIO itemDIO = new MaintenanceOrderUseItemDIO();
                    itemDIO.setItemId(p.getPartId());
                    itemDIO.setMasterId(p.getMasterId().intValue());
                    itemDIO.setMasterName(p.getMasterName());
                    itemDIO.setGoodsId(p.getPartCode());
                    itemDIO.setGoodsName(p.getPartName());
                    itemDIO.setCategOneId(p.getCategOneId());
                    itemDIO.setCategTwoId(p.getCategId());
                    itemDIO.setCategOneName(p.getCategOneName());
                    itemDIO.setCategTwoName(p.getCategName());
                    itemDIO.setNumber(p.getNumber());
                    itemDIO.setUnitName(p.getUnit());
                    itemDIO.setSourceType(OrderConsts.PART_TYPE_FACTORY);
                    // 如果厂商配件没有价格，则不传
                    if (Objects.nonNull(p.getPrice())) {
                        itemDIO.setPoPrice(p.getPrice().intValue());
                        itemDIO.setSalePrice(p.getPrice().intValue());
                    }
                    skuDIOList.add(itemDIO);
                });
                dio.setGoodsList(skuDIOList);
            } else {
                dio.setGoodsTypes(OrderConsts.PART_TYPE_SOURCING_IN);
                List<OrderPart> orderParts = orderPartService.listByOrderId(orderWork.getOrderId(),
                        OrderConsts.PART_TYPE_SOURCING_IN);

                List<MaintenanceOrderUseItemDIO> skuDIOList = Lists.newArrayList();
                orderParts.forEach(p -> {
                    MaintenanceOrderUseItemDIO itemDIO = new MaintenanceOrderUseItemDIO();
                    itemDIO.setSaleOrderId(p.getDrawId());
                    itemDIO.setMasterId(p.getMasterId());
                    itemDIO.setMasterName(p.getMasterName());
                    itemDIO.setGoodsId(p.getPartId());
                    itemDIO.setGoodsName(p.getPartName());
                    itemDIO.setCategOneId(p.getCategOneId());
                    itemDIO.setCategTwoId(p.getCategId());
                    itemDIO.setCategOneName(p.getCategOneName());
                    itemDIO.setCategTwoName(p.getCategName());
                    itemDIO.setNumber(p.getNumber());
                    itemDIO.setUnitName(p.getUnit());
                    itemDIO.setSourceType(OrderConsts.PART_TYPE_SOURCING_IN);
                    itemDIO.setPoPrice(p.getPurchasePrice());
                    itemDIO.setSalePrice(p.getPrice());
                    itemDIO.setImgSrc(p.getComparisonImgSrc());
                    itemDIO.setPhotoTime(p.getComparisonImgTime());
                    itemDIO.setPhotoLatitude(new BigDecimal(Optional.ofNullable(p.getLatitude()).orElse(0.0)));
                    itemDIO.setPhotoLongitude(new BigDecimal(Optional.ofNullable(p.getLongitude()).orElse(0.0)));
                    skuDIOList.add(itemDIO);
                });
                dio.setGoodsList(skuDIOList);
            }
            dio.setOperator(checkOutDto.getOperator());
            dio.setOperatorId(checkOutDto.getOperatorId());
            // 工单没有使用内采配件，则不调用
            if (CollectionUtil.isNotNullOrEmpty(dio.getGoodsList())) {
                boolean verifyPart = true;
                // 内采配件需要检验wms
                if (Objects.equals(dio.getGoodsTypes(), OrderConsts.PART_TYPE_SOURCING_IN)){
                    com.zmn.common.dto2.ResponseDTO<Boolean> responseDTO =
                            maintenanceOrderUseModifyRemoteService.verifyMaintenanceOrderUse(dio);
                    if (!responseDTO.isSuccess() || !responseDTO.getData()){
                        verifyPart = false;
                    }
                }
                if (verifyPart){
                    // 收单通知scm2使用的内采配件
                    String key = StringUtil.getRandomsString(32);
                    logger.info("#sync#scm2#finish#order#use#goods#sendMq key:{},message:{}", key, JSON.toJSONString(dio));
                    zmnMQSender.send(MessageQueueTopicConstant.ZMN_TOPIC_SCM2,
                            OmsMqTagConsts.SCM_FINISH_ORDER_USE_GOODS_MQ_TAGS, key, JSON.toJSONString(dio));
                } else {
                    throw new OmsBaseException("工单配件与WMS配件不一致，请重新核配件。");
                }
            }

            // 如果没有配件报销，则不调用
            List<OrderPart> orderParts = orderPartService.listByOrderId(orderWork.getOrderId());
            boolean isReimburseDoing = orderParts.stream().anyMatch(orderPart -> Objects.equals(orderPart.getReimburseStatus(), OrderConsts.PART_REIMBURSE_STATUS_DOING));
            /*if (Objects.equals(orderWork.getPartReimburseStatus(), OrderConsts.PART_REIMBURSE_STATUS_DOING)) {*/
            if (isReimburseDoing) {
                ScmPurchaseApplyDIO scmPurchaseApplyDIO = new ScmPurchaseApplyDIO();
                scmPurchaseApplyDIO.setSourceId(String.valueOf(checkOutDto.getOrderId()));
                // 收单通知scm2使用的外报和运杂
                String key = StringUtil.getRandomsString(32);
                logger.info("#sync#scm2#complete#order#sendMq key:{},message:{}", key,
                        JSON.toJSONString(scmPurchaseApplyDIO));
                zmnMQSender.send(MessageQueueTopicConstant.ZMN_TOPIC_SCM2, OmsMqTagConsts.SCM_COMPLETE_ORDER_MQ_TAGS,
                        key, JSON.toJSONString(scmPurchaseApplyDIO));
            }
        }
    }

    /**
     * 处理工单配件
     *
     * @param partVO
     * @param partAmount
     * @param partList
     * @return
     */
    private Integer processOrderPart(ZsAccountMasterPartVO partVO, Integer partAmount, List<OrderPart> partList) {
        if (partList != null && !partList.isEmpty()) {
            String masterName = partList.get(0).getMasterName();
            partVO.setMasterName(masterName);
            partAmount = partList.stream().mapToInt(part -> com.zmn.oms.common.utils.MathUtil.amountMultiplyNumber(
                    part.getPrice(), part.getNumber())).sum();
        }
        return partAmount;
    }

    /**
     * 获取补贴奖励
     *
     * @param orderWork
     * @return
     */
    // private ZsAccountSubsidyVO getAccountSubsidyVO(OrderWork orderWork) {
    //     ZsAccountSubsidyVO zsAccountSubsidyVO = new ZsAccountSubsidyVO();
    //     // 春节补贴比例。公司没配，取平台默认补贴
    //     com.zmn.common.dto2.ResponseDTO<BigDecimal> companySubsidyRemote = subsidyRuleConfigListRemoteService.getRuleConfigCompanyById(orderWork.getPlatWork(), orderWork.getManageCompanyId());
    //     zsAccountSubsidyVO.setSpringSubsidyRate(new BigDecimal(0));
    //     if (companySubsidyRemote.isSuccess() && companySubsidyRemote.getData() != null) {
    //         zsAccountSubsidyVO.setSpringSubsidyRate(companySubsidyRemote.getData());
    //     } else {
    //         com.zmn.common.dto2.ResponseDTO<BigDecimal> platSubsidyRemote = subsidyRuleConfigListRemoteService.getRuleConfigPlatById(orderWork.getPlatWork());
    //         if (platSubsidyRemote.isSuccess() && platSubsidyRemote.getData() != null) {
    //             zsAccountSubsidyVO.setSpringSubsidyRate(platSubsidyRemote.getData());
    //         }
    //     }
	//
    //     // 标准服务奖励。公司没配，取平台默认补贴
    //     if (!NumberUtil.isNullOrZero(orderWork.getMasterImageStatus())) {
    //         com.zmn.common.dto2.ResponseDTO<BonusConfigDRO> companyStandardRemote = bonusConfigListRemoteService.getBonusConfigAutoById(orderWork.getPlatWork(), orderWork.getManageCompanyId(), orderWork.getCityId());
    //         BonusConfigDRO bonusDRO = null;
    //         if (companyStandardRemote.isSuccess() && companyStandardRemote.getData() != null) {
    //             bonusDRO = companyStandardRemote.getData();
    //         }
    //         if (bonusDRO != null) {
    //             // 照片合格取正数奖励，不合格取负数奖励
    //             Integer bonus = Objects.equals(orderWork.getMasterImageStatus(), GlobalConsts.YES) ?
    //                     bonusDRO.getStandardBonus() :
    //                     bonusDRO.getStandardFine();
    //             zsAccountSubsidyVO.setBonus(bonus);
    //         }
    //     } else {
    //         // 无个人形象照片，奖励为0
    //         zsAccountSubsidyVO.setBonus(0);
    //     }
	//
    //     logger.info("[{}]工单补贴奖励[{}]", orderWork.getWorkId(), zsAccountSubsidyVO);
    //     return zsAccountSubsidyVO;
    // }
	//
    // private ZsAccountMasterBonusVO getAccountMasterBonusVO(OrderWork orderWork) throws OmsBaseException {
    //     ZsAccountMasterBonusVO accountMasterBonusVO = new ZsAccountMasterBonusVO();
    //     // 获取绩效配置
    //     logger.info("#order#account 获取绩效配置入参 plat:{}, manageCompanyId:{}, cityId:{}", orderWork.getPlat(),
    //             orderWork.getManageCompanyId(), orderWork.getCityId());
    //     com.zmn.common.dto2.ResponseDTO<BonusConfigDRO> configResponse = bonusConfigListRemoteService
    //             .getBonusConfigAutoById(orderWork.getPlatWork(), orderWork.getManageCompanyId(), orderWork.getCityId());
    //     logger.info("#order#account 获取绩效配置出参 {}", JSON.toJSONString(configResponse));
	//
    //     logger.info("#order#account 获取绩效入参 plat:{}, orderId:{}, workId", orderWork.getOrderId(), orderWork.getWorkId());
    //     com.zmn.common.dto2.ResponseDTO<OrderEffectivenessDRO> effectivenessResponse =
    //             orderEffectivenessListRemoteService
    //             .getByOrderIdAndWorkId(orderWork.getOrderId(), orderWork.getWorkId());
    //     logger.info("#order#account 获取绩效出参 {}", JSON.toJSONString(effectivenessResponse));
	//
    //     if (!configResponse.isSuccess() || !effectivenessResponse.isSuccess()) {
    //         throw new OmsBaseException("获取工程师相关绩效失败" + (configResponse.isSuccess() ?
    //                 effectivenessResponse.getMessage() :
    //                 configResponse.getMessage()));
    //     }
    //     BonusConfigDRO bonusConfigDRO = configResponse.getData();
    //     OrderEffectivenessDRO effectivenessDRO = effectivenessResponse.getData();
    //     if (Objects.isNull(bonusConfigDRO)) {
    //         throw new OmsBaseException("未配置激励奖");
    //     }
    //     if (Objects.isNull(effectivenessDRO)) {
    //         throw new OmsBaseException("指标未生成");
    //     }
	//
    //     // 准时上门激励金
    //     Integer ontimeArriveBonus = 0;
    //     if (!Objects.isNull(effectivenessDRO.getOnTimeVisitLevel())) {
    //         switch (effectivenessDRO.getOnTimeVisitLevel().getCode()) {
    //             case 1:
    //                 ontimeArriveBonus = bonusConfigDRO.getOnTimeVisitBonus();
    //                 break;
    //             case 3:
    //                 ontimeArriveBonus = bonusConfigDRO.getOnTimeVisitFineOne();
    //                 break;
    //             case 4:
    //                 ontimeArriveBonus = bonusConfigDRO.getOnTimeVisitFineThree();
    //                 break;
    //             case 5:
    //                 ontimeArriveBonus = bonusConfigDRO.getOnTimeVisitFineTwo();
    //                 break;
    //             default:
    //                 ontimeArriveBonus = 0;
    //         }
    //     }
    //     accountMasterBonusVO.setOntimeArriveBonus(Optional.ofNullable(ontimeArriveBonus).orElse(0));
    //     // 及时联系激励金
    //     Integer timelyContactBonus = 0;
    //     if (!Objects.isNull(effectivenessDRO.getOnTimeContact())) {
    //         if (Objects.equals(effectivenessDRO.getOnTimeContact().getCode(), GlobalConsts.YES)) {
    //             timelyContactBonus = bonusConfigDRO.getOnTimeContactBonus();
    //         } else if (Objects.equals(effectivenessDRO.getOnTimeContact().getCode(), GlobalConsts.NO)) {
    //             timelyContactBonus = bonusConfigDRO.getOnTimeContactFine();
    //         } else if (Objects.equals(effectivenessDRO.getOnTimeContact().getCode(), GlobalConsts.NONE)) {
    //             timelyContactBonus = 0;
    //         }
    //     }
    //     accountMasterBonusVO.setTimelyContactBonus(Optional.ofNullable(timelyContactBonus).orElse(0));
    //     // 准时完工激励金
    //     Integer ontimeFinishBonus = 0;
    //     if (!Objects.isNull(effectivenessDRO.getOnTimeComplete())) {
    //         if (Objects.equals(effectivenessDRO.getOnTimeComplete().getCode(), GlobalConsts.YES)) {
    //             ontimeFinishBonus = bonusConfigDRO.getOnTimeCompleteBonus();
    //         } else if (Objects.equals(effectivenessDRO.getOnTimeComplete().getCode(), GlobalConsts.NO)) {
    //             ontimeFinishBonus = bonusConfigDRO.getOnTimeCompleteFine();
    //         } else if (Objects.equals(effectivenessDRO.getOnTimeComplete().getCode(), GlobalConsts.NONE)) {
    //             ontimeFinishBonus = 0;
    //         }
    //     }
    //     accountMasterBonusVO.setOntimeFinishBonus(Optional.ofNullable(ontimeFinishBonus).orElse(0));
    //     // 是否24小时完成
    //     Integer onTimeTwentyFourCompleteBonus = 0;
    //     if (!Objects.isNull(effectivenessDRO.getOnTimeTwentyFourComplete())) {
    //         if (Objects.equals(effectivenessDRO.getOnTimeTwentyFourComplete().getCode(), GlobalConsts.YES)) {
    //             onTimeTwentyFourCompleteBonus = bonusConfigDRO.getCompleteInDayBonus();
    //         } else if (Objects.equals(effectivenessDRO.getOnTimeTwentyFourComplete().getCode(), GlobalConsts.NO)) {
    //             onTimeTwentyFourCompleteBonus = bonusConfigDRO.getCompleteInDayFine();
    //         } else if (Objects.equals(effectivenessDRO.getOnTimeTwentyFourComplete().getCode(), GlobalConsts.NONE)) {
    //             onTimeTwentyFourCompleteBonus = 0;
    //         }
    //     }
    //     accountMasterBonusVO.setCompleteIn24Bonus(Optional.ofNullable(onTimeTwentyFourCompleteBonus).orElse(0));
    //     // 标准照片激励金
    //     Integer standaredPicBonus = 0;
    //     if (Objects.equals(orderWork.getMasterImageStatus(), GlobalConsts.NONE)) {
    //         standaredPicBonus = 0;
    //     } else if (Objects.equals(orderWork.getMasterImageStatus(), GlobalConsts.YES)) {
    //         standaredPicBonus = bonusConfigDRO.getStandardBonus();
    //     } else if (Objects.equals(orderWork.getMasterImageStatus(), GlobalConsts.NO)) {
    //         standaredPicBonus = bonusConfigDRO.getStandardFine();
    //     }
    //     accountMasterBonusVO.setStandardPicBonus(Optional.ofNullable(standaredPicBonus).orElse(0));
    //     // 用户评价激励金
    //     Integer commentBonus = 0;
    //     if (!Objects.isNull(effectivenessDRO.getIsPraise())) {
    //         if (Objects.equals(effectivenessDRO.getIsPraise().getCode(), GlobalConsts.YES)) {
    //             commentBonus = bonusConfigDRO.getCommentBonus();
    //         } else if (Objects.equals(effectivenessDRO.getIsPraise().getCode(), GlobalConsts.NO)) {
    //             commentBonus = bonusConfigDRO.getCommentFine();
    //         } else if (Objects.equals(effectivenessDRO.getIsPraise().getCode(), GlobalConsts.NONE)) {
    //             commentBonus = 0;
    //         }
    //     }
    //     accountMasterBonusVO.setUserCommentBonus(Optional.ofNullable(commentBonus).orElse(0));
	//
    //     return accountMasterBonusVO;
    // }

    /**
     * 工单金额校验
     *
     * @param orderWork
     */
    @Override
    public void verifyOrderAmount(OrderWork orderWork) throws OmsBaseException {

        // 非新单不校验
        if (!Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_NEW)) {
            return;
        }

        // 保内单不校验
        if (Objects.equals(orderWork.getBizType(), com.zmn.consts.GlobalConsts.BIZ_TYPE_F)) {
            return;
        }

        List<OrderPay> orderPays = orderPayService.listOrderPayByOrderIdAndWorkId(orderWork.getOrderId(), orderWork.getWorkId())
                .stream()
                .filter(e -> !Objects.equals(e.getPayChannelId(), PayConsts.PAY_CHANNEL_PLATFORM_DISCOUNT) &&
                        !Objects.equals(e.getDuplicate(), com.zmn.consts.GlobalConsts.YES)
                )
                .collect(Collectors.toList());
        // 校验1，应收 = 已支付渠道代收 + 已支付平台预收 + 已支付定金 + 已支付师傅收款
        Integer factAmount = this.factAmount(orderWork);
        if (!Objects.equals(orderWork.getTotalAmount(), factAmount)) {
            int refundAmt = orderPays.stream()
                    .filter(e -> Objects.equals(e.getTradeType(), PayConsts.PAY_TRADE_TYPE_REFUND))
                    .mapToInt(e -> e.getAmount())
                    .sum();
            // 一口价原单退款（实际收款-退款）校验
            if (!Objects.equals(orderWork.getTotalAmount(), factAmount - refundAmt)) {
                throw new OmsBaseException("算账异常：已支付金额不等于应收金额");
            }
        }

        // 校验2，支付凭证和工单上记录款项校验（渠道代收例外）
		Integer paidPrepayAmt = 0;
        Integer paidDepositAmt = 0;
        Integer paidMasterAmt = 0;
        Integer warrantyAmt = 0;
        if (CollectionUtil.isNotNullOrEmpty(orderPays)) {
            paidPrepayAmt = orderPays.stream()
                    .filter(e -> Objects.equals(e.getAmountType(), OrderPayConsts.ORDER_PAY_PREPAY))
                    .mapToInt(e -> e.getAmount()).sum();
            paidDepositAmt = orderPays.stream()
                    .filter(e -> Objects.equals(e.getAmountType(), OrderPayConsts.ORDER_PAY_DEPOSIT)
                            || Objects.equals(e.getAmountType(), OrderPayConsts.ORDER_PAY_PROGRESS))
                    .mapToInt(e -> e.getAmount()).sum();
            paidMasterAmt = orderPays.stream()
                    .filter(e -> Objects.equals(e.getAmountType(), OrderPayConsts.ORDER_PAY_MASTER) && Objects
                            .equals(e.getTradeType(), PayConsts.PAY_TRADE_TYPE_INTIME)
                            && !Objects.equals(PayConsts.PAY_CHANNEL_PLATFORM_DEPOSIT,e.getPayChannelId())
                    ).mapToInt(e -> e.getAmount())
                    .sum();
            warrantyAmt = orderPays.stream()
                    .filter(e -> Objects.equals(e.getAmountType(), OrderPayConsts.ORDER_PAY_MASTER)
                            && Objects.equals( PayConsts.PAY_TRADE_TYPE_INTIME,e.getTradeType())
                            && Objects.equals(PayConsts.PAY_CHANNEL_PLATFORM_DEPOSIT,e.getPayChannelId())
                    ).mapToInt(e -> e.getAmount())
                    .sum();
        }
        Integer prepayAmt = Optional.ofNullable(orderWork.getPrepayAmount()).orElse(0);
        Integer depositAmt = Optional.ofNullable(orderWork.getDepositAmount()).orElse(0);
        Integer masterAmt = Optional.ofNullable(orderWork.getMasterAmount()).orElse(0);
        if (!Objects.equals(prepayAmt, (paidPrepayAmt+warrantyAmt)) || !Objects.equals(depositAmt, paidDepositAmt) || !Objects
                .equals(masterAmt, paidMasterAmt)) {
            throw new OmsBaseException("算账异常：已支付凭证不等于工单收款项");
        }

        // 校验3，订单金额 = 应收 + 优惠 校验
        Integer discountAmount = Optional.ofNullable(orderWork.getDiscountAmount()).orElse(0);
        Integer calcTotalAmt = MathUtil.sub(orderWork.getOriginalAmount(), discountAmount);
        calcTotalAmt += Optional.ofNullable(orderWork.getDiscountPrepayAmount()).orElse(0);
        calcTotalAmt -= Optional.ofNullable(orderWork.getPayDiscountAmount()).orElse(0);
        if (!Objects.equals(calcTotalAmt, orderWork.getTotalAmount())) {
            throw new OmsBaseException("算账异常：原价不等于应收+优惠");
        }

        // 校验4，订单金额 = 服务项表价格之和
        Integer serviceItemTotalPrice = 0;
        List<OrderServiceItem> orderServiceItems = orderServiceItemService.listByOrderId(orderWork.getOrderId());
        if (CollectionUtil.isNotNullOrEmpty(orderServiceItems)) {
            serviceItemTotalPrice = orderServiceItems.stream().filter(e -> e.getTotalPrice() != null)
                    .mapToInt(e -> e.getTotalPrice()).sum();
        }
        if (!Objects.equals(serviceItemTotalPrice, orderWork.getOriginalAmount())) {
            throw new OmsBaseException("算账异常：原价不等于服务项金额之和");
        }

        // 校验5，工单上冗余的优惠总价 = 优惠表各优惠之和
        Integer orderDiscountsAmt = 0;
        List<OrderDiscount> orderDiscounts = orderDiscountService.listByOrderId(orderWork.getOrderId());
        if (CollectionUtil.isNotNullOrEmpty(orderDiscounts)) {
            orderDiscountsAmt = orderDiscounts.stream().filter(e -> e.getAmount() != null).mapToInt(e -> e.getAmount())
                    .sum();
        }
        if (!Objects.equals(orderDiscountsAmt, discountAmount)) {
            throw new OmsBaseException("算账异常：优惠金额异常");
        }

        // 校验6，工单上冗余的配件总价 = 内 + 外 + 运
        Integer partTotalAmt = Optional.ofNullable(orderWork.getPartAmount()).orElse(0);
        Integer inSourAmt = Optional.ofNullable(orderWork.getInSourcingAmount()).orElse(0);
        Integer outSourAmt = Optional.ofNullable(orderWork.getOutSourcingAmount()).orElse(0);
        Integer deliverAmt = Optional.ofNullable(orderWork.getDeliverAmount()).orElse(0);
        if (partTotalAmt != inSourAmt + outSourAmt + deliverAmt) {
            throw new OmsBaseException("算账异常：配件金额异常");
        }

        // 校验7，工单上冗余的 内 + 外 + 运 总额 = 配件表金额
        Integer orderInSourAmt = 0;
        Integer orderOutSourAmt = 0;
        Integer orderDeliverAmt = 0;
        List<OrderPart> orderParts = orderPartService.listByOrderId(orderWork.getOrderId());
        if (CollectionUtil.isNotNullOrEmpty(orderParts)) {
            orderInSourAmt = orderParts.stream()
                    .filter(e -> Objects.equals(e.getPartType(), OrderConsts.PART_TYPE_SOURCING_IN)
                            && e.getPrice() != null && e.getNumber() != null)
                    .mapToInt(e -> com.zmn.oms.common.utils.MathUtil.amountMultiplyNumber(e.getPrice(), e.getNumber()))
                    .sum();
            orderOutSourAmt = orderParts.stream()
                    .filter(e -> Objects.equals(e.getPartType(), OrderConsts.PART_TYPE_SOURCING_OUT)
                            && e.getPrice() != null && e.getNumber() != null)
                    .mapToInt(e -> com.zmn.oms.common.utils.MathUtil.amountMultiplyNumber(e.getPrice(), e.getNumber()))
                    .sum();
            orderDeliverAmt = orderParts.stream()
                    .filter(e -> Objects.equals(e.getPartType(), OrderConsts.PART_TYPE_DELIVER) && e.getPrice() != null
                            && e.getNumber() != null).mapToInt(e -> com.zmn.oms.common.utils.MathUtil.amountMultiplyNumber(
                                    e.getPrice(), e.getNumber())).sum();
        }
        if (!Objects.equals(inSourAmt, orderInSourAmt) || !Objects.equals(outSourAmt, orderOutSourAmt) || !Objects
                .equals(deliverAmt, orderDeliverAmt)) {
            throw new OmsBaseException("算账异常：配件金额异常2");
        }
    }

    private List<ZsUpdateOrderInternalPriceServiceItemVO> personToServiceItemVO(List<OrderServiceItem> serviceItem) {
        if (serviceItem == null) {
            return Collections.EMPTY_LIST;
        }

        List<ZsUpdateOrderInternalPriceServiceItemVO> list = new ArrayList<>(serviceItem.size());
        for (OrderServiceItem orderServiceItem : serviceItem) {
            ZsUpdateOrderInternalPriceServiceItemVO zsUpdateOrderInternalPriceServiceItemVO = new ZsUpdateOrderInternalPriceServiceItemVO();

            if (orderServiceItem.getProExtId() != null) {
                zsUpdateOrderInternalPriceServiceItemVO.setProExtId(String.valueOf(orderServiceItem.getProExtId()));
            }
            zsUpdateOrderInternalPriceServiceItemVO.setServItemId(orderServiceItem.getServItemId());
            zsUpdateOrderInternalPriceServiceItemVO.setServItemName(orderServiceItem.getServItemName());
            zsUpdateOrderInternalPriceServiceItemVO.setNumber(orderServiceItem.getNumber());
            zsUpdateOrderInternalPriceServiceItemVO.setItemPrice(orderServiceItem.getItemPrice());
            zsUpdateOrderInternalPriceServiceItemVO.setInternalSettlementPrice(orderServiceItem.getInternalSettlementPrice());
            zsUpdateOrderInternalPriceServiceItemVO.setInternalTotalPrice(orderServiceItem.getInternalTotalPrice());
            list.add(zsUpdateOrderInternalPriceServiceItemVO);
        }

        return list;
    }

    /**
     * 获取实付金额
     *
     * @param orderWork
     * @return
     */
    private Integer factAmount(OrderWork orderWork) {
        Integer factAmount = 0;
        if (Objects.equals(orderWork.getChannelPrepayStatus(), PayConsts.PAY_STATUS_DONE) && !NumberUtil
                .isNullOrZero(orderWork.getChannelPrepayAmount())) {
            factAmount = factAmount + orderWork.getChannelPrepayAmount().intValue();
        }
        if (Objects.equals(orderWork.getPrepayStatus(), PayConsts.PAY_STATUS_DONE) && !NumberUtil
                .isNullOrZero(orderWork.getPrepayAmount())) {
            factAmount = factAmount + orderWork.getPrepayAmount().intValue();
        }
        if (Objects.equals(orderWork.getDepositStatus(), PayConsts.PAY_STATUS_DONE) && !NumberUtil
                .isNullOrZero(orderWork.getDepositAmount())) {
            factAmount = factAmount + orderWork.getDepositAmount().intValue();
        }
        if (Objects.equals(orderWork.getMasterPayStatus(), PayConsts.PAY_STATUS_DONE) && !NumberUtil
                .isNullOrZero(orderWork.getMasterAmount())) {
            factAmount = factAmount + orderWork.getMasterAmount().intValue();
        }
        if (NumberUtil.isNotNullOrZero(orderWork.getDiscountPrepayAmount())) {
            factAmount = factAmount + orderWork.getDiscountPrepayAmount().intValue();
        }
        if (Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_REFUND) && !NumberUtil.isNullOrZero(orderWork.getRefundAmount())) {
            factAmount = MathUtil.sub(factAmount, orderWork.getRefundAmount());
        }
        return factAmount;
    }

    /**
     * 是否erp算账
     *
     * @param orderWork
     * @return
     */
    public boolean needErpAccount(OrderWork orderWork) {

        Integer platWork = orderWork.getPlatWork();
        if (Objects.equals(orderWork.getManageCompanyId(), com.zmn.oms.common.constant.CompanyConsts.ZMN_VIRTUAL_MANAGE_COMPANY_ID)) {
            logger.info("啄木鸟虚拟服务公司[{}]不支持erp算账", orderWork.getManageCompanyId());
            return false;
        }

        if (Objects.equals(platWork, GlobalConsts.PLAT_MARK_ZMN) || Objects
                .equals(platWork, GlobalConsts.PLAT_MARK_YEYX) || Objects
                .equals(platWork, GlobalConsts.PLAT_MARK_CNHB)) {
            return true;
        } else {
            logger.info("[{}]平台不支持erp算账", platWork);
            return false;
        }
    }

    private BigDecimal getRate(BigDecimal a, BigDecimal b) {
        if (a.equals(ZERO) || b.equals(ZERO) || a.equals(ZERO.setScale(1, HALF_UP)) || b.equals(ZERO.setScale(1, HALF_UP))) {
            return ZERO.setScale(2, HALF_UP);
        }
        return a.divide(b, 4, HALF_UP).movePointRight(2);
    }
}
